const { QueryPage, mapArrayAttributes } = require('../../../utils')
Parse.Cloud.define('getRoles', async (req, res) => {
  const user = req.user
  if (!user) {
    return res.error('请先登录')
  }
  const permission = { sessionToken: user.getSessionToken() }
  const { pageSize, currentPage, where } = req.params
  // queryPage
  const queryPage = new QueryPage(Parse.Role, pageSize, currentPage)
  const query = queryPage.getQuery()
  query.include('users')
  // 查询条件
  if (where) {
    const { name } = where
    if (name) {
      query.matches('name', name)
    }
  }
  try {
    // 查询结果
    const result = await queryPage.fetch(['name'], (data, item) => {
      data.findUsers = item.get('users').query().find(permission)
      data.findRoles = item.get('roles').query().find(permission)
      return data
    }, permission)
    // 查找users和roles
    const data = result.data
    for (let i = 0, len = data.length; i < len; i++) {
      const current = data[i]
      const users = await current.findUsers
      const roles = await current.findRoles
      current.users = mapArrayAttributes(users, ['username'])
      current.roles = mapArrayAttributes(roles, ['name'])
      delete current.findRoles
      delete current.findUsers
    }

    res.success(result)
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})
